package TFIDF;

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * 接受的数据  <count,1>         <希望_肖申克的救赎,1>
 * 输出      <count,sum>         <希望_肖申克的救赎,TF>
 */
public class RedTest01 extends Reducer<Text, DoubleWritable, Text, DoubleWritable> {
    Text k = new Text();
    DoubleWritable v = new DoubleWritable();

    @Override
    protected void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
        double sum = 0;
        //求出总评论数，或者求出一个词在一个评论里的次数
        for (DoubleWritable value : values) {
            sum += value.get();
        }
        if ("count".equals(key.toString())) {
            v.set(sum);
            //输出总评论数
            context.write(key, v);
        } else {
            String[] datas = key.toString().split("_");
            double commonLen = Double.parseDouble(datas[2]);
            v.set(sum / commonLen);
            k.set(datas[1] + "_" + datas[0]);
            context.write(k, v);
        }
    }
}
